package controller.admin;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import controller.admin.base.BaseAdminController;
import enums.RoleType;
import model.Role;
import model.User;
import service.MenuService;
import service.RoleService;
import service.UserRoleService;

public class AdminRoleController extends BaseAdminController {

	@Inject RoleService roleService;
	@Inject MenuService menuService ;
	@Inject UserRoleService userRoleService ;
	
    public void list() {
    	List<Record> list = roleService.findAll();
    	renderJson("list", list);
    }
    
    /**
     * 根据用户的最高权限来配置权限
     */
    public void info() {
    	Integer id = getParaToInt("id");
        Role role = Role.dao.findById(id);
        User loginUser = getLoginUser() ;
        List<Record> list = userRoleService.findUserToMenu(loginUser);
        set("data", role);
        set("menuList", list );
        set("typeList", RoleType.toList());
        renderJson();
	}
    
    @Before(Tx.class)
    public void save() {
    	try {
    		Role role = getModel(Role.class , "x") ;
        	renderJson( roleService.save( role , getLoginUser() ) );
		} catch (Exception e) {
			e.printStackTrace();
			renderFail();
			throw e ;
		}
	}
    
    @Before(Tx.class)
    public void delete() {
    	try {
    		Long id = getParaToLong("id");
        	renderJson(roleService.delete(id));
		} catch (Exception e) {
			e.printStackTrace();
			renderFail();
			throw e ;
		}
    	
    }
}
